﻿using System.Collections.Generic;
using System.Windows;
using System.Linq;
using System.Windows.Controls;

namespace WordStat.ArticlesService
{
    /// <summary>
    /// Interaction logic for ArticlesEditWindow.xaml
    /// </summary>
    public partial class ArticlesEditWindow : Window
    {
        public ArticlesEditWindow()
        {
            InitializeComponent();

            _dataSrv = new ArticleService();

            InitSources();

        }

        private ArticleService _dataSrv;

        private void InitSources()
        {
            var rootItem = _dataSrv.GetItem();

            _treeView.Items.Add(rootItem);

            rootItem.IsSelected = true;
        }

        private void _closeBtn_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void _treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var allItems = e.NewValue as AllItemsViewItem;

            if (allItems != null)
            {
                var data = _dataSrv.GetAllArticles();

                _dataGrid.ItemsSource = data.Select(articleAuthorData => new Record { ArticleTitle = articleAuthorData.ArticleTitle, Author = articleAuthorData.Author, ArticleId = articleAuthorData.ArticleId }).ToList();

                return;
            }

            var sourceItem = e.NewValue as SourceItemView;

            if (sourceItem != null)
            {
                var data = _dataSrv.GetArticlesBySource(sourceItem.Source);

                return;
            }
        }

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            var checkBox = sender as CheckBox;

            if (null == checkBox)
                return;

            if (!checkBox.IsChecked.HasValue)
                return;

            foreach (var item in _dataGrid.Items.OfType<Record>())
                item.IsSelected = checkBox.IsChecked.Value;
        }

        private void _deleteBtn_Click(object sender, RoutedEventArgs e)
        {
            var articleService = new ArticleService();

            foreach (var item in _dataGrid.Items.OfType<Record>())
            {
                articleService.DeleteArticle(item.ArticleId);
            }
        }
    }
}
